package server.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DataSourceConfig
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2021/12/21 上午12:12
 * @Version V1.0
 * @Since JDK 11
 */
@Configuration
public class DataSourceConfig {

    @Bean
    public DataSource readDataSource(ReadDataSourceProp readDataSourceProp){
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setUsername(readDataSourceProp.getUsername());
        hikariDataSource.setPassword(readDataSourceProp.getPassword());
        hikariDataSource.setJdbcUrl(readDataSourceProp.getJdbcUrl());
        hikariDataSource.setDriverClassName(readDataSourceProp.getDriverClassName());
        return hikariDataSource;
    }

    @Bean
    public DataSource writeDataSource(WriteDataSourceProp writeDataSourceProp){
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setUsername(writeDataSourceProp.getUsername());
        hikariDataSource.setPassword(writeDataSourceProp.getPassword());
        hikariDataSource.setJdbcUrl(writeDataSourceProp.getJdbcUrl());
        hikariDataSource.setDriverClassName(writeDataSourceProp.getDriverClassName());
        return hikariDataSource;
    }

    @Bean
    public CustomRoutingDataSource abstractRoutingDataSource(@Qualifier("readDataSource") DataSource readDataSource,@Qualifier("writeDataSource") DataSource writeDataSource){
        CustomRoutingDataSource customRoutingDataSource = new CustomRoutingDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("read",readDataSource);
        targetDataSources.put("write",writeDataSource);
        customRoutingDataSource.setTargetDataSources(targetDataSources);
        return customRoutingDataSource;
    }




}
